﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace Mozlite.Components
{
    /// <summary>
    /// 用户Cookie。
    /// </summary>
    public class UserCookie
    {
        /// <summary>
        /// 初始化用户Cookie。
        /// </summary>
        /// <param name="user">用户实例对象。</param>
        public UserCookie(User user)
        {
            this.User = user;
        }

        /// <summary>
        /// 获取用户实例。
        /// </summary>
        public User User { get; private set; }

        private string GetCookieName(string name)
        {
            if(this.User.IsAnonymous)
                return "usrid.0.{0}".FormatWith(name);
            return "usrid.{0}.{1}".FormatWith(User.UserID, name);
        }

        /// <summary>
        /// 获取Cookie值。
        /// </summary>
        /// <typeparam name="T">Cookie值类型。</typeparam>
        /// <param name="name">返回名称。</param>
        /// <param name="defaultValue">默认值。</param>
        /// <returns>返回Cookie的值。</returns>
        public T Get<T>(string name, T defaultValue = default(T))
        {
            return Cookies.GetCookie<T>(GetCookieName(name), defaultValue);
        }

        /// <summary>
        /// 删除Cookie。
        /// </summary>
        /// <param name="name">Cookie名称。</param>
        public void Delete(string name)
        {
            Cookies.DeleteCookie(GetCookieName(name));
        }

        /// <summary>
        /// 设置Cookie。
        /// </summary>
        /// <param name="name">名称。</param>
        /// <param name="value">值。</param>
        /// <param name="expiredSeconds">过期描述。</param>
        public void Set(string name, object value, double expiredSeconds)
        {
            name = GetCookieName(name);
            HttpCookie cookie = new HttpCookie(name, value.ToSafeString());
            cookie.Expires = DateTime.Now.AddSeconds(expiredSeconds);
            Cookies.SetCookie(cookie);
        }

        /// <summary>
        /// 设置验证码Cookie。
        /// </summary>
        /// <param name="key">验证码键。</param>
        /// <param name="value">验证码值。</param>
        public void SetValidCode(string key, string value)
        {
            Set(key, value, Consts.MinuteSeconds * 20);
        }

        /// <summary>
        /// 验证码。
        /// </summary>
        /// <param name="key">验证码键。</param>
        /// <param name="value">验证码值。</param>
        /// <returns>返回验证结果。</returns>
        public bool IsVCValid(string key, string value)
        {
            string validCode = Get<string>(key);
            if (string.IsNullOrEmpty(validCode))
                return false;
            return validCode.IsCaseInsensitiveEqual(value);
        }
    }
}
